const { sequelize } = require('../utils/database');
const { 
  User, 
  UserProfile, 
  Activity, 
  Badge, 
  Feed, 
  ActivityParticipant, 
  UserFollow, 
  FeedLike, 
  FeedComment 
} = require('../models');
const bcrypt = require('bcryptjs');

async function createSeedData() {
  try {
    console.log('开始创建种子数据...');

    // 创建更多用户
    const additionalUsers = [
      {
        username: 'david',
        email: 'david@campus.com',
        password_hash: await bcrypt.hash('password123', 10),
        bio: '计算机科学专业，热爱编程和人工智能',
        avatar_url: '/uploads/default-avatar.svg',
        is_active: true
      },
      {
        username: 'emma',
        email: 'emma@campus.com',
        password_hash: await bcrypt.hash('password123', 10),
        bio: '艺术设计学院，喜欢摄影和设计',
        avatar_url: '/uploads/default-avatar.svg',
        is_active: true
      },
      {
        username: 'frank',
        email: 'frank@campus.com',
        password_hash: await bcrypt.hash('password123', 10),
        bio: '体育学院，篮球队队长',
        avatar_url: '/uploads/default-avatar.svg',
        is_active: true
      },
      {
        username: 'grace',
        email: 'grace@campus.com',
        password_hash: await bcrypt.hash('password123', 10),
        bio: '医学院学生，志愿者服务爱好者',
        avatar_url: '/uploads/default-avatar.svg',
        is_active: true
      },
      {
        username: 'henry',
        email: 'henry@campus.com',
        password_hash: await bcrypt.hash('password123', 10),
        bio: '商学院，创业社团成员',
        avatar_url: '/uploads/default-avatar.svg',
        is_active: true
      },
      {
        username: 'ivy',
        email: 'ivy@campus.com',
        password_hash: await bcrypt.hash('password123', 10),
        bio: '文学院，诗社会长',
        avatar_url: '/uploads/default-avatar.svg',
        is_active: true
      }
    ];

    const newUsers = await User.bulkCreate(additionalUsers);
    console.log('创建了', newUsers.length, '个新用户');

    // 为新用户创建个人画像
    const userProfiles = newUsers.map((user, index) => {
      const interests = [
        ['编程', '人工智能', '游戏开发'],
        ['设计', '摄影', '艺术'],
        ['篮球', '健身', '运动'],
        ['医学', '志愿服务', '健康'],
        ['创业', '商业', '投资'],
        ['文学', '诗歌', '阅读']
      ];

      return {
        user_id: user.id,
        interests: interests[index] || ['学习', '社交'],
        activity_preferences: {
          types: ['学术', '体育', '社交', '艺术'],
          time: 'evening',
          location: 'campus'
        },
        location_preference: '校园内',
        preferred_time_slots: ['19:00-21:00', '14:00-17:00'],
        activity_frequency: 'high',
        social_level: 'extrovert'
      };
    });

    await UserProfile.bulkCreate(userProfiles);
    console.log('创建了', userProfiles.length, '个用户画像');

    // 创建更多活动
    const additionalActivities = [
      {
        title: '摄影技巧分享会',
        description: '邀请专业摄影师分享摄影技巧和后期处理方法',
        location: '艺术楼201',
        start_time: new Date('2025-06-20T14:00:00Z'),
        end_time: new Date('2025-06-20T16:00:00Z'),
        max_participants: 30,
        current_participants: 0,
        created_by: 6, // emma
        status: 'published',
        tags: ['摄影', '艺术', '技能分享'],
        latitude: 39.90420000,
        longitude: 116.40740000
      },
      {
        title: '篮球友谊赛',
        description: '不同学院之间的篮球友谊比赛，增进友谊',
        location: '体育馆',
        start_time: new Date('2025-06-25T16:00:00Z'),
        end_time: new Date('2025-06-25T18:00:00Z'),
        max_participants: 20,
        current_participants: 0,
        created_by: 7, // frank
        status: 'published',
        tags: ['篮球', '体育', '竞赛'],
        latitude: 39.90420000,
        longitude: 116.40740000
      },
      {
        title: '创业项目路演',
        description: '学生创业项目展示和投资人对接活动',
        location: '创新创业中心',
        start_time: new Date('2025-06-30T09:00:00Z'),
        end_time: new Date('2025-06-30T17:00:00Z'),
        max_participants: 100,
        current_participants: 0,
        created_by: 9, // henry
        status: 'published',
        tags: ['创业', '商业', '投资'],
        latitude: 39.90420000,
        longitude: 116.40740000
      },
      {
        title: '诗歌朗诵晚会',
        description: '原创诗歌作品朗诵和文学交流活动',
        location: '文学院礼堂',
        start_time: new Date('2025-07-05T19:00:00Z'),
        end_time: new Date('2025-07-05T21:00:00Z'),
        max_participants: 80,
        current_participants: 0,
        created_by: 10, // ivy
        status: 'published',
        tags: ['文学', '诗歌', '艺术'],
        latitude: 39.90420000,
        longitude: 116.40740000
      },
      {
        title: '医学急救培训',
        description: '基础医学急救知识和技能培训',
        location: '医学院实验室',
        start_time: new Date('2025-07-10T10:00:00Z'),
        end_time: new Date('2025-07-10T12:00:00Z'),
        max_participants: 25,
        current_participants: 0,
        created_by: 8, // grace
        status: 'published',
        tags: ['医学', '急救', '技能培训'],
        latitude: 39.90420000,
        longitude: 116.40740000
      }
    ];

    const newActivities = await Activity.bulkCreate(additionalActivities);
    console.log('创建了', newActivities.length, '个新活动');

    // 创建活动参与记录
    const participations = [];
    const allUsers = await User.findAll();
    const allActivities = await Activity.findAll();

    // 为每个活动随机分配参与者
    for (const activity of allActivities) {
      const participantCount = Math.floor(Math.random() * Math.min(10, activity.max_participants)) + 1;
      const randomUsers = allUsers
        .filter(user => user.id !== activity.created_by)
        .sort(() => 0.5 - Math.random())
        .slice(0, participantCount);

      for (const user of randomUsers) {
        participations.push({
          user_id: user.id,
          activity_id: activity.id,
          status: Math.random() > 0.3 ? 'registered' : 'attended',
          registered_at: new Date()
        });
      }

      // 更新活动参与人数
      await activity.update({ current_participants: participantCount });
    }

    await ActivityParticipant.bulkCreate(participations);
    console.log('创建了', participations.length, '个活动参与记录');

    // 创建用户关注关系
    const follows = [];
    for (let i = 0; i < allUsers.length; i++) {
      for (let j = 0; j < allUsers.length; j++) {
        if (i !== j && Math.random() > 0.7) { // 30%的概率关注其他用户
          follows.push({
            follower_id: allUsers[i].id,
            following_id: allUsers[j].id,
            status: 'active'
          });
        }
      }
    }

    await UserFollow.bulkCreate(follows);
    console.log('创建了', follows.length, '个关注关系');

    // 创建动态
    const feeds = [
      {
        user_id: 5, // david
        content: '刚完成了我的第一个AI项目，用深度学习识别校园植物，效果还不错！期待和大家分享经验。',
        feed_type: 'post',
        is_public: true,
        likes_count: 0,
        comments_count: 0
      },
      {
        user_id: 6, // emma
        content: '今天在校园拍了一组秋天的照片，光影效果特别棒。摄影真的是记录美好时光的最好方式。',
        feed_type: 'post',
        is_public: true,
        likes_count: 0,
        comments_count: 0
      },
      {
        user_id: 7, // frank
        content: '篮球队今天训练很棒，大家配合越来越默契了。下周的比赛一定能拿下！💪',
        feed_type: 'post',
        is_public: true,
        likes_count: 0,
        comments_count: 0
      },
      {
        user_id: 8, // grace
        content: '参加了社区志愿服务活动，帮助老人体检。能用自己的医学知识帮助他人真的很有意义。',
        feed_type: 'post',
        is_public: true,
        likes_count: 0,
        comments_count: 0
      },
      {
        user_id: 9, // henry
        content: '创业计划书终于完成了！从市场调研到商业模式设计，每一步都充满挑战。期待路演！',
        feed_type: 'post',
        is_public: true,
        likes_count: 0,
        comments_count: 0
      },
      {
        user_id: 10, // ivy
        content: '写了一首关于校园生活的诗，"梧桐叶落知秋意，书声朗朗伴青春"。文字真的能表达内心最深的感受。',
        feed_type: 'post',
        is_public: true,
        likes_count: 0,
        comments_count: 0
      }
    ];

    const newFeeds = await Feed.bulkCreate(feeds);
    console.log('创建了', newFeeds.length, '个动态');

    // 为动态添加点赞和评论
    const likes = [];
    const comments = [];

    for (const feed of newFeeds) {
      // 随机点赞
      const likers = allUsers
        .filter(user => user.id !== feed.user_id)
        .sort(() => 0.5 - Math.random())
        .slice(0, Math.floor(Math.random() * 5) + 1);

      for (const liker of likers) {
        likes.push({
          user_id: liker.id,
          feed_id: feed.id
        });
      }

      // 随机评论
      const commenters = allUsers
        .filter(user => user.id !== feed.user_id)
        .sort(() => 0.5 - Math.random())
        .slice(0, Math.floor(Math.random() * 3) + 1);

      const commentTexts = [
        '太棒了！加油！',
        '很有意思，学到了',
        '支持你！',
        '期待看到更多分享',
        '真不错，继续保持',
        '很有启发性',
        '赞一个！'
      ];

      for (const commenter of commenters) {
        comments.push({
          user_id: commenter.id,
          feed_id: feed.id,
          content: commentTexts[Math.floor(Math.random() * commentTexts.length)],
          is_deleted: false
        });
      }

      // 更新动态统计
      await feed.update({
        likes_count: likers.length,
        comments_count: commenters.length
      });
    }

    await FeedLike.bulkCreate(likes);
    await FeedComment.bulkCreate(comments);
    console.log('创建了', likes.length, '个点赞和', comments.length, '个评论');

    // 创建一些徽章
    const badges = [
      {
        user_id: 5,
        activity_id: 2, // AI技术讲座
        badge_name: '技术先锋',
        badge_description: '参与AI技术讲座并表现优秀',
        badge_image_url: '/uploads/default-badge.svg',
        rarity: 'rare',
        attributes: JSON.stringify({ skill: 'AI', level: 'intermediate' }),
        status: 'minted',
        minted_at: new Date()
      },
      {
        user_id: 6,
        activity_id: 5, // 摄影分享会
        badge_name: '摄影达人',
        badge_description: '摄影技巧分享会优秀参与者',
        badge_image_url: '/uploads/default-badge.svg',
        rarity: 'common',
        attributes: JSON.stringify({ skill: 'photography', level: 'advanced' }),
        status: 'minted',
        minted_at: new Date()
      },
      {
        user_id: 7,
        activity_id: 6, // 篮球友谊赛
        badge_name: '运动健将',
        badge_description: '篮球比赛最佳球员',
        badge_image_url: '/uploads/default-badge.svg',
        rarity: 'epic',
        attributes: JSON.stringify({ sport: 'basketball', achievement: 'mvp' }),
        status: 'minted',
        minted_at: new Date()
      }
    ];

    await Badge.bulkCreate(badges);
    console.log('创建了', badges.length, '个徽章');

    console.log('种子数据创建完成！');
  } catch (error) {
    console.error('创建种子数据失败:', error);
  }
}

module.exports = { createSeedData };

// 如果直接运行此脚本
if (require.main === module) {
  createSeedData()
    .then(() => {
      console.log('种子数据脚本执行完成');
      process.exit(0);
    })
    .catch(error => {
      console.error('种子数据脚本执行失败:', error);
      process.exit(1);
    });
} 